package p.ithorns.framework.common.mmap;

import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * MappedIO
 *
 * @author liuhaitao
 * @date 2024/4/8 15:54
 * @since 1.0.0
 */
public interface MappedCleanable {

    default void clean(final MappedByteBuffer mbb) {
        if (mbb == null) {
            return;
        }

        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            try {
                Method cleanerMethod = mbb.getClass().getMethod("cleaner");
                cleanerMethod.setAccessible(true);
                // sun.misc.Cleaner cleaner = (sun.misc.Cleaner) cleanerMethod.invoke(mbb, new Object[0]);
                // cleaner.clean();
                Object cleanerObject = cleanerMethod.invoke(mbb);
                Method cleanMethod = cleanerObject.getClass().getDeclaredMethod("clean");
                cleanMethod.invoke(cleanerObject);
            } catch (Exception e) {
                System.out.println("关闭MappedByteBuffer句柄错误! ");
                e.printStackTrace();
            }
            return null;
        });
    }

}